package com.oohoo.spacestationspringbootstarter.config;

import com.oohoo.spacestationspringbootstarter.dto.query.config.CommonConfig;
import com.oohoo.spacestationspringbootstarter.dto.query.exception.DtoQueryException;
import com.oohoo.spacestationspringbootstarter.dto.query.jpa.JpaButler;
import com.oohoo.spacestationspringbootstarter.dto.query.Butler;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * @Description:
 * @Author: leeoohoo@gmail.com
 * @CreateTime: 2022/8/10
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableConfigurationProperties(value = SpaceStationProperties.class)
public class SpaceStationAutoConfiguration {

    public static String TASK_EXECUTOR_NAME = null;

    public static Integer DEFAULT_BATCH_SIZE = 50;
    private final ApplicationContext applicationContext;







    public SpaceStationAutoConfiguration(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SpringUtils springUtils(SpaceStationProperties stationProperties) {
        TASK_EXECUTOR_NAME = stationProperties.getTaskExecutorName();
        Integer defaultBatchSize = Integer.valueOf(stationProperties.getDefaultBatchSize());

        DEFAULT_BATCH_SIZE =  defaultBatchSize <= 0  ? defaultBatchSize : DEFAULT_BATCH_SIZE;
        SpringUtils springUtils = new SpringUtils();
        springUtils.setApplicationContext(applicationContext);
        return springUtils;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Scope(scopeName = "prototype")
    public Butler butler() {
        EntityManagerFactory factory = SpringUtils.getBean(EntityManagerFactory.class);
        if(Objects.isNull(factory)) {
            throw new DtoQueryException("初始化 EntityManagerFactory 异常，EntityManagerFactory加载失败");
        }
        EntityManager entityManager = factory.createEntityManager();
        return new JpaButler(entityManager);
    }

    @Bean
    public CommonConfig commonConfig(SpaceStationProperties stationProperties) {
        final CommonConfig commonConfig = new CommonConfig();
        commonConfig.setEnableDeleted(stationProperties.getEnableDeleted());
        commonConfig.setDeletedValue(Short.valueOf(stationProperties.getDeletedValue()));
        return commonConfig;
    }
}
